Run()
{
   echo "Run $@"
   $@
   if [ $? -ne 0 ];then
      echo "Failed: [$@]"
      exit 0
   fi
}

ARCH="arm"
VERSION="v1.3.5"
PORT=8886
APP_NAME="verysync"
DEPLOY_DIR_NAME=${APP_NAME}
TAR_DIR=${APP_NAME}-linux-${ARCH}-${VERSION}
TAR_FILE=${TAR_DIR}.tar.gz
DEPLOY_PARENT_DIR=/mnt/HD/HD_a2/app
DEPLOY_DIR=$DEPLOY_PARENT_DIR/$DEPLOY_DIR_NAME

if [ ! -d $DEPLOY_PARENT_DIR ];then
    Run mkdir -p $DEPLOY_PARENT_DIR
fi

##get the lastest version info
LASTEST_VERSION=`curl http://www.verysync.com/shell/latest`
if [ -n "$LASTEST_VERSION" ];then
   echo "lastest version was $LASTEST_VERSION"
   VERSION=$LASTEST_VERSION
fi

CURR_VERSION=""
if [ -f $DEPLOY_DIR/$APP_NAME ];then
    CURR_VERSION=`$DEPLOY_DIR/$APP_NAME -version|grep -oe 'v[1-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*'`
fi

if [ "$CURR_VERSION" != "$VERSION" ];then
    URL=http://releases-cdn.verysync.com/releases/${VERSION}/$TAR_FILE
	Run wget -O $DEPLOY_PARENT_DIR/$TAR_FILE $URL
	
	Run tar -xf $DEPLOY_PARENT_DIR/$TAR_FILE -C $DEPLOY_PARENT_DIR	
	if [ -d $DEPLOY_DIR ];then
		#the dest folder already existed, so updated it
		cp -fpr $DEPLOY_PARENT_DIR/$TAR_DIR/* $DEPLOY_DIR/
	else
		#the first execute
		Run mv $DEPLOY_PARENT_DIR/$TAR_DIR $DEPLOY_DIR
	fi
else
	echo "The lastest version[$VERSION] was same as current version[$CURR_VERSION]"
	echo "not need to update binrary"
fi

CFG_PATH=$DEPLOY_DIR/conf
LOG_PATH=$DEPLOY_DIR/log
if [ ! -d $LOG_PATH ];then
    Run mkdir -p $CFG_PATH $LOG_PATH
fi


cat<<EOF > $DEPLOY_DIR/$APP_NAME.start
pid=\`ps -fe|grep $APP_NAME|grep -v grep|grep -v \$\$|grep -v '$APP_NAME\.start'|awk '{print \$1}'\`
if [ -z "\$pid" ];then
   $DEPLOY_DIR/$APP_NAME -home $CFG_PATH -logfile $LOG_PATH/$APP_NAME.log -gui-address "http://0.0.0.0:${PORT}" >/dev/null 2>&1 &
else
   echo "$APP_NAME is already running with pid[\$pid]" >&2
fi
EOF


cat<<EOF > $DEPLOY_DIR/$APP_NAME.stop
pids=\`ps -fe|grep $APP_NAME|grep -v grep|grep -v \$\$|grep -v '$APP_NAME\.stop'|awk '{print \$1}'|tr "\n" " "\`
if [ -n "\$pids" ];then
    echo "killing \$pids ..."
    kill \$pids
	while [ 1 ];
	do
		sleep 1
		printf "."
		pids=\`ps -fe|grep $APP_NAME|grep -v grep|grep -v \$\$|grep -v '$APP_NAME\.stop'|awk '{print \$1}'|tr "\n" " "\`
		if [ -z "\$pids" ];then
			echo "OK"
			break
		fi
	done
fi

EOF


Run chmod +x $DEPLOY_DIR/$APP_NAME.start $DEPLOY_DIR/$APP_NAME.stop

cat<<EOF
Usage:
start versync: $DEPLOY_DIR/$APP_NAME.start

stop versync: $DEPLOY_DIR/$APP_NAME.stop

EOF

